package phenix.com.phenixdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;

import de.greenrobot.event.EventBus;
import phenix.com.phenixdemo.event.EventAsync;
import phenix.com.phenixdemo.event.EventBackground;
import phenix.com.phenixdemo.event.EventMain;
import phenix.com.phenixdemo.event.EventPost;
import phenix.com.phenixdemo.mvp.view.ActivityLogin;
import phenix.com.phenixdemo.ui.ActivityAA_;
import phenix.com.phenixdemo.ui.BaseActivity;

public class ActivityMain extends BaseActivity {

    ListView mListView;
    ArrayAdapter<String> adapter;
    ArrayAdapter<String> demoAdapter;
    private boolean isDemo = false;

    public static final String[] itemTitles = {
            ">>\t\tMaster Activity",
            ">>\t\tFullscreen Activity",
            ">>\t\tLogin Activity",
            ">>\t\tDetail Activity",
            ">>\t\tNavigationDrawer Activity",
            ">>\t\tScrolling Activity",
            ">>\t\tSettings Activity",
            ">>\t\tTabbed Activity",
            ">>\t\tBasic Activity"



    };

    public static final String[] demoTitles = {
            ">>\t\tAndroidAnnotations(AA)注解框架"
    };

    final Class<AppCompatActivity>[] clazzs = new Class[]{
            ActivityMaster_.class,
            ActivityFullscreen.class,
            ActivityLogin.class,
            ItemListActivity.class,
            ActivityNavigationDrawer.class,
            ActivityScrolling.class,
            ActivitySettings.class,
            ActivityTabbed.class,
            ActivityBasic.class
    };

    final Class<AppCompatActivity>[] clzEntry = new Class[]{
            ActivityAA_.class
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        mListView = (ListView) findViewById(R.id.listView);
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, itemTitles);
        demoAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, demoTitles);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isDemo){
                    toggle(clzEntry[position-mListView.getHeaderViewsCount()]);
                }else{
                    toggle(clazzs[position-mListView.getHeaderViewsCount()]);
                }


            }
        });
        if(null != getIntent()){
            int position = getIntent().getIntExtra("clicked_position",-1);
            if(position!= -1 )toggle(clazzs[position]);// ActivityAA_.intent(this).extra("extraData","data").start();

        }

        final TextView demoEntry = (TextView) findViewById(R.id.demo_entry);
        demoEntry.setVisibility(View.VISIBLE);
        demoEntry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isDemo = !isDemo;
                mListView.setAdapter(isDemo?demoAdapter:adapter);
                demoEntry.setText(isDemo?getText(R.string.s_entry):getText(R.string.s_demo_entry));
            }
        });
    }



    public void toggle(Class<AppCompatActivity> cls) {
        Intent i = new Intent(this, cls);
        if (cls.equals(ActivityAA_.class))
            i.putExtra("extraData","来自"+this.getClass().getSimpleName()+"的问候");
        startActivity(i);
    }

    /**
     *它和ThreadModel中的PostThread对应，这个也是默认的类型，当使用这种类型时，回调函数和发起事件的函数会在同一个线程中执行
     * @param event
     */
    public void onEvent(EventPost event){
//        Snackbar.make(mListView,"EventPost。。。",Snackbar.LENGTH_SHORT).show();
        Log.i(">>>>>>>Event<<<<<<<<","onEvent+++++++++++++");
    }

    /**当使用这种类型时，回调函数会在主线程中执行，这个在Android中非常有用，因为在Android中禁止在子线程中修改UI
     * EventBus 测试
     * @param event
     */
    public void onEventMainThread(EventMain event){
        Snackbar.make(mListView,"onEventMainThread。。。",Snackbar.LENGTH_SHORT).setAction("Action",null).show();
        Log.i(">>>>>>>Event<<<<<<<<","onEventMainThread+++++++++++++");
    }

    /**
     * 当使用这种类型时，如果事件发起函数在主线程中执行，
     * 那么回调函数另启动一个子线程，如果事件发起函数在子线程执行，那么回调函数就在这个子线程执行
     *
     * 执行在子线程，如果发布者是子线程则直接执行，如果发布者不是子线程，则创建一个再执行
     * 此处可能会有线程阻塞问题。
     * @param event
     */
    public void onEventBackgroundThread(EventBackground event){
//        Toast.makeText(ActivityMain.this, "onEventBackgroundThread...", Toast.LENGTH_SHORT).show();
        Log.i(">>>>>>>Event<<<<<<<<","onEventBackgroundThread+++++++++++++");

        //TODO OkHttpClient GET请求方式
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com").build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {//异步方式
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i(">>>OkHttpClient<<<<","onFailure+++++++++++++");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                Log.i(">>>OkHttpClient<<<<","onResponse++"+response.body().string());
                EventBus.getDefault().post(new EventPost());
            }
        });

//        try {
//            Response response = call.execute();//同步方式
//            Log.i(">>>OkHttpClient<<<<","onResponse++"+response.body().string());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }


    /**
     * 当使用这种类型时，不管事件发起函数在哪里执行，都会另起一个线程去执行回调
     *  执行在在一个新的子线程
     * 适用于多个线程任务处理， 内部有线程池管理。
     * @param event
     */
    public void onEventAsync(EventAsync event){
//        Toast.makeText(ActivityMain.this, "onEventAsync...", Toast.LENGTH_SHORT).show();
        Log.i(">>>>>>>Event<<<<<<<<","onEventAsync+++++");
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url("http://www.baidu.com").build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {//异步方式
//            @Override
//            public void onFailure(Request request, IOException e) {
//                Log.i(">>>OkHttpClient<<<<","onFailure+++++++++++++");
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                Log.i(">>>OkHttpClient<<<<","onResponse++"+response.body().string());
//                EventBus.getDefault().post(new EventPost());
//            }
//        });


    }


    /**
     * OkHttpClient  POST提交Json数据
     */
    public String postJson(String url, String json) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSON,json);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
    /**
     * OkHttpClient  POST提交Key-Value数据
     */
    public String postKV(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormEncodingBuilder()
                .add("platform", "android")
                .add("name", "bug")
                .add("subject", "XXXXXXXXXXXXXXX")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
